# -*- coding: utf-8 -*-
from selenium.common.exceptions import NoSuchElementException
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
import pyautogui
import datetime
import time


class YoupaiSpider():
    name = 'youpaiSpider'
    height=670
    width=300
    # driver = webdriver.Chrome()
    index_url = 'http://yppmh.com/'
    house_url = "http://yppmh.com/auction_house"
    login_url = "http://yppmh.com/login"
    # users = ({"name": "17795179212", "pwd": "74664521hw"},)
    user = {"name": "17795179212", "pwd": "74664521hw"}
    cookies={}
    timeoffset=datetime.timedelta(hours=2)
    moringstr='2021-01-01 10:00:00'
    afternostr = '2021-01-01 14:00:00'
    nightstr = '2021-01-01 19:00:00'
    moring=datetime.datetime.strptime(moringstr,"%Y-%m-%d %H:%M:%S")
    afterno=datetime.datetime.strptime(afternostr,"%Y-%m-%d %H:%M:%S")
    night=datetime.datetime.strptime(nightstr,"%Y-%m-%d %H:%M:%S")
    option = webdriver.ChromeOptions()
    option.add_argument(
        "User-Agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5")
    option.add_argument("detach=True")
    driver = webdriver.Chrome(chrome_options=option)

    def begin(self):

        self.driver.set_window_size(self.width, self.height)
        print("程序开始...")
        # 登录
        self.login(self.user)
        self.getHouse()
        self.getOrder()

    def login(self,user):
        # self.driver.get("https://www.taobao.com")
        self.driver.get(url=self.login_url)
        WebDriverWait(self.driver, 5).until(ec.presence_of_element_located((By.XPATH,'//span[contains(text(), "密码登陆")]')));
        # time.sleep(2)
        print("开始登陆...")
        try:
            # 跳转到密码登录
            self.driver.find_element_by_xpath('//span[contains(text(), "密码登陆")]').click()
        except NoSuchElementException:
            print("没有找到密码登录按钮")
        if self.driver.find_element_by_xpath("//input[@placeholder='填写登录密码']"):
           self.driver.find_element_by_xpath("//input[@placeholder='输入手机号码']").send_keys(user["name"])
           self.driver.find_element_by_xpath("//input[@placeholder='填写登录密码']").send_keys(user["pwd"])
           self.driver.find_element_by_xpath('//div[@class="logon"]').click()
           self.cookies = self.driver.get_cookies()
        # 登录完成后跳转到目标页面
        # self.driver.get(targerUrl)

    def getHouse(self):
        self.driver.get(self.house_url)
        # time.sleep(2)
        # 等待
        WebDriverWait(self.driver, 2).until(ec.presence_of_element_located((By.XPATH,'//span[contains(text(), "晚间场")]')));
        print("进入抢单主页...")
        # if driver.current_url.find("http://yppmh.com/login") > 0:
        #     self.login(driver,self.user,self.house_url)
        mtime = datetime.datetime.now()
        targetPate=None
        if self.driver.current_url == self.house_url :
            if mtime.strftime('%H:%M:%S.%f') >= self.moring.strftime('%H:%M:%S.%f') and mtime.strftime('%H:%M:%S.%f') <= (self.moring + self.timeoffset).strftime('%H:%M:%S.%f'):
                targetPate=self.driver.find_element_by_xpath('//span[contains(text(), "上午场")]')
            elif  mtime.strftime('%H:%M:%S.%f') >= self.afterno.strftime('%H:%M:%S.%f') and mtime.strftime('%H:%M:%S.%f') <= (self.afterno + self.timeoffset).strftime('%H:%M:%S.%f'):
                targetPate=self.driver.find_element_by_xpath('//span[contains(text(), "下午场")]')
            elif mtime.strftime('%H:%M:%S.%f') >= self.night.strftime('%H:%M:%S.%f') and mtime.strftime('%H:%M:%S.%f') <= (self.night + self.timeoffset).strftime('%H:%M:%S.%f'):
                targetPate=self.driver.find_element_by_xpath('//span[contains(text(), "晚间场")]')
        targetPate = self.driver.find_element_by_xpath('//span[contains(text(), "晚间场")]')
        targetPate.click()

    def getOrder(self):
        # WebDriverWait(driver, 5).until(ec.presence_of_element_located((By.XPATH,'//span[contains(text(), "晚间场")]')));
        print("开始抢单...")
        pyautogui.click(self.width/2+50, 700, 2, 0.25, button='left')
        time.sleep(1)
        pyautogui.scroll(-10000)
        time.sleep(1)
        pyautogui.scroll(-10000)
        time.sleep(4)
        elments = self.driver.find_elements_by_xpath('//div[@class="text"]')
        targerOrder=None
        for el in elments:
            price= float(el.find_element_by_xpath('//div[contains(text(), "￥")]').text[1:])
            print(price)
            if price > 10000:
                targerOrder=el
                break
        targerOrder.click()

    def openPay(self):
        print("开始支付...")
        self.driver.find_element_by_xpath("//div[@class='footer']").click()
        self.driver.find_element_by_xpath("").click()
        time.sleep(3600)

    def wait_order(self):
        while True:
            mtime = datetime.datetime.now()
            if mtime.strftime('%H:%M:%S.%f') >= self.moring.strftime('%H:%M:%S.%f') and mtime.strftime('%H:%M:%S.%f') <= (self.moring + self.timeoffset).strftime('%H:%M:%S.%f'):
                self.getHouse()
                self.getOrder()
            elif  mtime.strftime('%H:%M:%S.%f') >= self.afterno.strftime('%H:%M:%S.%f') and mtime.strftime('%H:%M:%S.%f') <= (self.afterno + self.timeoffset).strftime('%H:%M:%S.%f'):
                self.getHouse()
                self.getOrder()
            elif mtime.strftime('%H:%M:%S.%f') >= self.night.strftime('%H:%M:%S.%f') and mtime.strftime('%H:%M:%S.%f') <= (self.night + self.timeoffset).strftime('%H:%M:%S.%f'):
                self.getHouse()
                self.getOrder()
            else:continue


    def orderClose(self):
        time.sleep(50)
        print("退出...")
        self.driver.close()

if __name__ == '__main__':
    spider=YoupaiSpider()
    spider.begin()





